//
//  WTAudioObject.m
//  录音功能开发
//
//  Created by awifi on 4/1/18.
//  Copyright © 2018年 awifi. All rights reserved.
//

#import "WTAudioObject.h"
#import <AVFoundation/AVFoundation.h>

@interface WTAudioObject()
/** 录音对象*/
@property(nonatomic ,strong) AVAudioRecorder *recorder;
@property(nonatomic,strong)AVAudioPlayer *player;
@property(nonatomic,strong)AVAudioSession *mySession;
@end

@implementation WTAudioObject
+(id)shareInstance{
    static WTAudioObject *sharedInstance = nil;

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc]init];
    });
    return sharedInstance;
}
-(void)createRecordWith:(NSString *)urlstr{
    AVAudioSession *session =[AVAudioSession sharedInstance];
    NSError *sessionError;
    [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
    
    if (session == nil) {
        
        NSLog(@"Error creating session: %@",[sessionError description]);
        
    }else{
        [session setActive:YES error:nil];
        
    }
    
    self.mySession = session;

    
    //1.创建录音文件存放路径
    NSString * path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.pcm",urlstr]];
    NSURL * url = [NSURL URLWithString:path];
    
    //2.录音设置
    NSMutableDictionary * recordSettings = [[NSMutableDictionary alloc]init];
    //设置编码格式
    [recordSettings setValue:[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];
    //采样率
    [recordSettings setValue:[NSNumber numberWithFloat:16000] forKey:AVSampleRateKey];
    //通道数
    [recordSettings setValue:[NSNumber numberWithInt:2] forKey: AVNumberOfChannelsKey];
    //音频质量，采集质量
    [recordSettings setValue:[NSNumber numberWithInt:AVAudioQualityMax] forKey:AVEncoderAudioQualityKey];
    self.recorder = [[AVAudioRecorder alloc]initWithURL:url settings:recordSettings error:nil];
    [self.recorder prepareToRecord];
    [self.recorder record];
}
-(void)startAudioWith:(NSString *)str{
    [self createRecordWith:str];
}

-(void)resumeRecordAudio {
    [self.recorder record];
}

-(void)stopAudio{
    [self.recorder stop];
}
-(void)playAudioWithPath:(NSString *)pathUrl{
    //1.创建录音文件存放路径
//    NSString * path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.pcm",pathUrl]];
    NSURL * url = [NSURL URLWithString:pathUrl];
    self.player = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];
    [self.mySession setCategory:AVAudioSessionCategoryPlayback error:nil];
    [self.player play];
}
@end
